import angular from 'angular'
import '@yunke/jquery_pagination'
import 'angular-ui'
import '../common/nav'
import authorize from '../authorize'
import config from '../config'
import '../contract/contract-common'
import util from '@yunke/core/util'
import '../common/row-toolbar'
import ui from '@yunke/core/ui'
import $ from 'jquery'
import {chain} from 'lodash'
import permision from "../../permission";

const api_prefix = window.G_CONFIG['api_prefix']
const filterDataStatus = [{
    name: '全部', selected: true, value: ''
}, {
    name: '草稿', value: '0'
}, {
    name: '未审核', value: '1'
}, {
    name: '已审核', value: '2'
}, {
    name: '作废', value: '-1'
}]
const filterDataCategory = [{
    name: '全部', selected: true, value: ''
}, {
    name: '广告合同', value: '1'
}, {
    name: 'SaaS合同', value: '2'
}]
const filterDataCategoryForAD = [{
    name: '广告合同', selected: true, value: '1'
}]
const filterDataCategoryForSAAS = [{
    name: 'SaaS合同', selected: true, value: '2'
}]
const filterDataNature = [{
    property_name: '全部', selected: true, property_id: ''
}]
const filterDataType = [{
    name: '全部', selected: true, value: ''
}, {
    name: '销售合同', value: '1'
}, {
    name: '服务合同', value: '2'
}];
const filterDataCities = [{
    areaName: '全部', selected: true, areaId: ''
}];
const filterStatementType = [{
    name: '全部', selected: true, value: ''
}, {
    name: '合同签约明细表', value: '1'
}, {
    name: '合同回款明细表', value: '2'
}, {
    name: '签约产品明细表', value: '3'
}, {
    name: '收入明细表', value: '4'
}, /*{
    name: '签约业绩明细表', value: '5'
}, {
    name: '回款业绩明细表', value: '6'
}, {
    name: '交付业绩明细表', value: '7'
},*/ {
    name: '应收款项明细表', value: '8'
}, {
    name: '纸质合同统计表', value: '9'
}, {
    name: '特批发票', value: '12'
}, {
    name: '特批授权', value: '13'
}, {
    name: '已开票未回款明细表', value: '14'
}, {
    name: '坏账明细表', value: '15'
}, {
    name: '代理合同未上传标的物明细表', value: '10'
}, {
    name: '收入结转表',
    value: '16',
    href: 'http://report.mysoft.net.cn:8080/WebReport8/ReportServer?reportlet=Report%2Fyl%2F%5B4e91%5D%5B5ba2%5D%5B6536%5D%5B5165%5D%5B7ed3%5D%5B8f6c%5D%5B8868%5D.cpt',
}, {
    name: '收入&回款&应收对应表', value: '17'
}];
const filterTimeType = [{
    name: '全部', selected: true, value: '0'
}, {
    name: '签约日期', value: '1'
}, {
    name: '录入日期', value: '2'
}, {
    name: '签约业绩所属日期', value: '3'
}, {
    name: '回款业绩所属日期', value: '4'
}, {
    name: '导出日期', value: '5'
}];
angular.module('Contract', ['ngUI', 'myNav', 'ContractCommonService', 'rowToolbar'])
    .controller('contractListCtrl', ['$scope', 'contractCommonService', 'appservice', function ($scope, contractCommonService, appservice) {
        appservice.name = '明源云客-合同管理';
        $scope.filterDataStatus = filterDataStatus;
        $scope.filterDataNature = filterDataNature;
        $scope.filterDataCategory = filterDataCategory;
        $scope.filterDataCategoryForAD = filterDataCategoryForAD;
        $scope.filterDataCategoryForSAAS = filterDataCategoryForSAAS;

        //获取合同性质列表
        contractCommonService.getContractNatures(data => {
            $.merge($scope.filterDataNature, data);
            $scope.$applyAsync();
        });

        $scope.filterDataType = filterDataType
        $scope.filterDataCities = filterDataCities
        //获取合同区域列表
        contractCommonService.getContractAreas(function (data) {
            $.merge($scope.filterDataCities, data);
            $scope.$applyAsync();
        });

        //获取权限列表
        // permision.getData((data) => {
        //     $scope.userAuthList = data;
        // });

        //合同列表
        $scope.contracts = [];

        //报表类型
        $scope.filterStatementType = filterStatementType

        $scope.filterTimeType = filterTimeType

        $scope.changeStatus = () => $scope.query.execute();
        $scope.changeCategory = () => $scope.query.execute();
        $scope.changeNature = () => $scope.query.execute();
        $scope.changeType = () => $scope.query.execute();
        $scope.changeCity = () => $scope.query.execute();
        $scope.changeStatement = () => $scope.query.execute();
        $scope.changeTimeType = timeType => {
            $scope.showTimeSelected = timeType.value !== 0 ? 2 : 0
        };

        $scope.submitVerify = function (contract) {
            util.confirm('确定要提交复核吗?', {
                ok() {
                    util.myAjax({
                        url: api_prefix + "/contract/submit-review",
                        type: "POST",
                        context: this,
                        data: {contractId: contract.contract_id},
                        success(json) {
                            if (json.retCode === "0") {
                                contract.contract_status = 1;
                                $scope.$applyAsync();

                            } else {
                                util.alert("提交复核失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        };
        $scope.cancelVerify = function (contract) {
            util.confirm('确定要撤销复核吗?', {
                ok() {
                    util.myAjax({
                        url: api_prefix + "/contract/cancel-review",
                        type: "POST",
                        context: this,
                        data: {contractId: contract.contract_id},
                        success(json) {
                            if (json.retCode === "0") {
                                contract.contract_status = 0;
                                $scope.$applyAsync();
                            } else {
                                util.alert("撤销复核失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        };
        $scope.confirmVerify = function (contract) {
            util.confirm('确定要复核此合同吗?', {
                ok() {
                    util.myAjax({
                        url: api_prefix + "/contract/audit-review",
                        type: "POST",
                        context: this,
                        data: {contractId: contract.contract_id},
                        success(json) {
                            if (json.retCode === "0") {
                                contract.contract_status = 2;
                                $scope.$applyAsync();

                            } else {
                                util.alert("合同复核失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        };
        $scope.cancelContract = function (contract) {
            util.confirm('确定要作废合同吗?', {
                ok() {
                    util.myAjax({
                        url: api_prefix + "/contract/cancel-contract",
                        type: "POST",
                        context: this,
                        data: {contractId: contract.contract_id},
                        success(json) {
                            if (json.retCode === "0") {
                                contract.is_cancelled = 1;
                                $scope.$applyAsync();

                            } else {
                                util.alert("作废合同失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        };
        $scope.deleteContract = function (contract) {
            util.confirm('确定要删除合同吗?', {
                ok() {
                    util.myAjax({
                        url: api_prefix + "/contract/delete-contract",
                        type: "POST",
                        context: this,
                        data: {contractId: contract.contract_id},
                        success(json) {
                            console.log(json);
                            if (json.retCode === "0") {
                                $scope.query.execute();

                            } else {
                                util.alert("删除合同失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        };

        const toDate = str => {
            const arr = str.split("-");
            return new Date(arr[0], arr[1], arr[2]);
        }

        //dateStr1 and dateStr2 is a formatted string like yyyy-MM-dd
        const compareDate = (startDate, endDate) => toDate(startDate) > toDate(endDate)

        //查询条件
        $scope.getQueryParams = function (page) {
            const parms = {
                keyword: $scope.query.keyword,
                beginDate: $scope.query.beginDate,
                endDate: $scope.query.endDate,
                pageIndex: page || 1,
                pageSize: config.pager().pageSize
            };
            if (compareDate(parms.beginDate, parms.endDate)) {
                util.alert('开始时间不得大于结束时间');
            } else {
                parms.status = chain($scope.filterDataStatus).find("selected").get("value").value()

                if ($scope.userAuthList == undefined) {
                    parms.category = 3;
                } else {
                    if ($scope.userAuthList.indexOf('1701') !== -1 && $scope.userAuthList.indexOf('1702') !== -1) {
                        parms.category = chain($scope.filterDataCategory).find("selected").get("value").value()
                    } else if ($scope.userAuthList.indexOf('1701') !== -1 && $scope.userAuthList.indexOf('1702') === -1) {
                        parms.category = chain($scope.filterDataCategoryForAD).find("selected").get("value").value()
                    } else if ($scope.userAuthList.indexOf('1701') === -1 && $scope.userAuthList.indexOf('1702') !== -1) {
                        parms.category = chain($scope.filterDataCategoryForSAAS).find("selected").get("value").value()
                    } else {
                        parms.category = 3;
                    }
                }


                parms.property = chain($scope.filterDataNature).find("selected").get("property_id").value()
                parms.areaId = chain($scope.filterDataCities).find("selected").get("areaId").value()
                parms.reportType = chain($scope.filterStatementType).find("selected").get("value").value()
                parms.timeType = chain($scope.filterTimeType).find("selected").get("value").value()
                return parms;
            }
        };
        //查询
        $scope.query = {
            keyword: '',
            beginDate: '',
            endDate: '',
            execute(page) {
                const parms = $scope.getQueryParams(page);
                util.myAjax({
                    url: api_prefix + "/contract/get-contract-list",
                    type: "GET",
                    context: this,
                    data: parms,
                    success(json) {
                        if (json.retCode === "0") {
                            $scope.contracts = json.data.items;
                            $scope.$applyAsync();

                            $scope.startPageIndex = (parms.pageIndex - 1) * 10;
                            $('#pagination').pagination(parseInt(json.data.total), {
                                current_page: parms.pageIndex - 1,
                                num_edge_entries: 1, //边缘页数
                                num_display_entries: 4, //主体页数
                                callback(page_index) {
                                    //page_index += 1; // 分页控件从 0 开始，后台从 1 开始
                                    $scope.startPageIndex = (page_index - 1) * 10;
                                    $scope.query.execute(page_index);
                                },
                                items_per_page: config.pager().pageSize //每页显示1项
                            });

                        } else {
                            this.showTip("获取合同列表失败：" + json.errMsg);
                        }
                    }
                });
            }
        };

        window.ui = ui;

        /**
         * 导出
         */
        $scope.downloadExcel = function ($event) {
            const parms = $scope.getQueryParams();
            delete parms.pageIndex;
            delete parms.pageSize;
            delete parms.sortBy;
            delete parms.sortAsc;
            ui.loading(null, '导出中...');
            const target = $event.target
            $(target).prop('disabled', true);

            util.myAjax({
                url: api_prefix + '/contract/export-contract',
                data: parms,
                type: 'get',
                success(data) {
                    let url;
                    const userGuid = authorize.getUserInfo().userGuid;
                    //报表类型
                    const filterStatement = $.grep($scope.filterStatementType, function (o) {
                        return o.selected;
                    });
                    if (filterStatement.length) {
                        if (+filterStatement[0].value === 1) {
                            url = data.data;
                        } else {
                            url = 'http://ci-yunketest.oss-cn-shenzhen.aliyuncs.com/hetong-data_' + userGuid + '.xls?_=' + new Date().getTime();
                        }
                    } else {
                        url = 'http://ci-yunketest.oss-cn-shenzhen.aliyuncs.com/hetong-data_' + userGuid + '.xls?_=' + new Date().getTime();
                    }


                    util.showDialog({
                        title: '导出成功',
                        fixed: true,
                        width: 350,
                        content: '<div style="padding:10px;">文件导出成功，<a href="' + url + '" target="_blank">请下载</a>!</div>',
                        cancelDisplay: true
                    });
                },
                error() {
                    util.alert('文件导出失败');
                },
                complete() {
                    ui.removeLoading();
                    $(target).prop('disabled', false);
                }
            });
        };


        $scope.onExportPaperContractEditShow = function ($dialog, $dialogScope) {
            /**
             * 下载导入模板
             */
            $dialogScope.handleDownloadTemplate = function () {
                var url = api_prefix + "/contract/download-contract-doc-store-template";
                var data = {};
                util.download(url, data);
            };

            /**
             * 导入合同文档
             */
            $('#importContractDoc').fileupload({
                dataType: 'json',
                url: api_prefix + "/contract/import-contract-doc-store",
                acceptFileTypes: /(\.|\/)(xls?x)$/i,
                maxFileSize: 10000000,
                done: function (e, data) {
                    var res = data.result;
                    if (res.retCode == '0') {
                        util.alert(res.data || '导入成功');
                    } else {
                        util.alert(res.errMsg);
                    }
                },
                fail: function (e, data) {
                    util.alert('系统维护，请稍候重试');
                }
            });
        }

        //附件上传初始化
        setTimeout(function () {
            $('#fileupload').fileupload({
                dataType: 'json',
                url: api_prefix + "/contract/import-repayment",
                add(e, data) {
                    data.submit();
                    ui.loading('', '正在上传…');
                },
                done(e, data) {
                    const res = data.result;
                    if (res.retCode === "0") {
                        util.alert("导入成功");
                    } else {
                        util.alert("导入失败:" + res.errMsg);
                    }
                },
                fail() {
                    util.alert("上传失败");
                },
                always() {
                    ui.removeLoading();
                }
            });
        }, 0);

        permision.getData((data) => {
            $scope.userAuthList = data;
            $scope.query.execute();
        });

    }]);
